<?php

namespace api\modules\v1\forms\rbac;

use Yii;
use yii\base\Model;
use common\models\member\Member;
use common\models\rbac\Menu;
use common\models\rbac\Action;
use common\models\rbac\Module;
use common\models\rbac\RolePermission;

/**
 * 动作
 *
 * Class ActionForm
 * @package api\modules\v1\forms\rbac
 */
class ActionForm extends Model
{
    /**
     * 动作ID
     *
     * @var
     */
    public $id;

    /**
     * 模块ID
     *
     * @var
     */
    public $module_id;

    /**
     * 菜单ID
     *
     * @var
     */
    public $menu_id;

    /**
     * 动作名
     *
     * @var
     */
    public $name;

    /**
     * 动作路由
     *
     * @var
     */
    public $flag;

    /**
     * 动作状态
     *
     * @var
     */
    public $status;

    /**
     * 菜单排序
     *
     * @var
     */
    public $sort;

    /**
     * 用户ID
     *
     * @var
     */
    public $member_id;


    /**
     * 动作信息
     *
     * @var array
     */
    protected $action;


    public function rules()
    {
        return [
            // 参数验证
            [['member_id', 'name', 'module_id', 'menu_id', 'flag', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create']],
            [['member_id', 'id', 'name', 'module_id', 'menu_id', 'flag', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['member_id', 'id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['delete']],

            [['member_id'], 'checkMemberId', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'delete']],
            [['id'], 'checkAction', 'skipOnEmpty' => false, 'on' => ['edit', 'delete']],
            [['name'], 'checkName', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['module_id'], 'checkModuleId', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['menu_id'], 'checkMenuId', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['flag'], 'checkFlag', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['sort'], 'checkSort', 'skipOnEmpty' => true, 'on' => ['create', 'edit']],
            [['status'], 'checkStatus', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        $scenarios['create'] = ['member_id', 'name', 'module_id', 'menu_id', 'flag', 'sort', 'status'];

        // 编辑
        $scenarios['edit'] = ['member_id', 'id', 'name', 'module_id', 'menu_id', 'flag', 'sort', 'status'];

        // 删除
        $scenarios['delete'] = ['member_id', 'id'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'member_id' => '用户ID',
            'id' => '动作ID',
            'name' => '动作名称',
            'module_id' => '模块名称',
            'menu_id' => '菜单名称',
            'flag' => '路由',
            'sort' => '排序',
            'status' => '状态',
        ];
    }

    /**
     * 检验用户UID
     *
     * @param $attribute
     * @return bool
     */
    public function checkMemberId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $member = Yii::$app->services->member->getInfo(['id' => $this->member_id]);
        if ($member['is_super'] != Member::IS_SUPER_YES) {
            $this->addError($attribute, '非超管，无权限操作');
            return true;
        }
    }

    /**
     * 检验动作信息
     *
     * @param $attribute
     * @return bool
     */
    public function checkAction($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $action = $this->getAction();
        if (!$action) {
            $this->addError($attribute, '动作不存在');
            return true;
        }

        if ($action->status == Action::STATUS_DELETE) {
            $this->addError($attribute, '菜单已删除，无法操作');
            return true;
        }

        if (($this->getScenario() == 'edit' && $this->status == Action::STATUS_INVALID)
            || $this->getScenario() == 'delete') {
            $rolePermission = Yii::$app->services->rolePermission->findInfo([
                'permission_id' => $this->id,
                'permission_type' => RolePermission::PERMISSION_TYPE_ACTION,
            ]);

            if ($rolePermission) {
                $this->addError($attribute, "该动作行为有人员或角色绑定，不能禁用");
                return true;
            }
        }
    }

    /**
     * 校验动作名称
     *
     * @param $attribute
     */
    public function checkName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->name);
        if ($len > 10) {
            $this->addError($attribute, '动作名称过长，最多10个字');
            return true;
        }

        // 是否检验
        $isCheck = true;
        if ($this->getScenario() == 'edit') {
            $action = $this->getAction();
            // 动作参数未改变【跳过】
            if ($action->name == $this->name && $action->flag == $this->flag && $action->menu_id == $this->menu_id) {
                $isCheck = false;
            }
        }

        if ($isCheck) {
            $actionInfo = Yii::$app->services->action->findInfo([
                'name' => $this->name,
                'flag' => $this->flag,
                'menu_id' => $this->menu_id,
                'status' => [Menu::STATUS_INVALID, Menu::STATUS_ENABLE],
            ]);

            if ($actionInfo) {
                $this->addError($attribute, "动作【{$this->name}】已存在");
                return true;
            }
        }
    }

    /**
     * 校验模块ID
     *
     * @param $attribute
     */
    public function checkModuleId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $module = Yii::$app->services->module->findById($this->module_id);
        if (!$module) {
            $this->addError($attribute, '模块不存在');
            return true;
        }

        if ($module->status != Module::STATUS_ENABLE) {
            $this->addError($attribute, '模块未启用，无法操作');
            return true;
        }
    }

    /**
     * 校验菜单ID
     *
     * @param $attribute
     */
    public function checkMenuId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $menu = Yii::$app->services->menu->findById($this->menu_id);
        if (!$menu) {
            $this->addError($attribute, '参数错误[menu_id_error]');
            return true;
        }

        if ($menu->status != Menu::STATUS_ENABLE) {
            $this->addError($attribute, '菜单未启用，无法操作');
            return true;
        }

        if ($menu->module_id != $this->module_id) {
            $this->addError($attribute, '非当前模块菜单');
            return true;
        }
    }

    /**
     * 校验动作路由
     *
     * @param $attribute
     */
    public function checkFlag($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = strlen($this->flag);
        if ($len > 80) {
            $this->addError($attribute, '动作路由过长，最多80个字节');
            return true;
        }
    }

    /**
     * 校验动作排序
     *
     * @param $attribute
     */
    public function checkSort($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->sort < 0) {
            $this->addError($attribute, '排序值不能小于0');
            return true;
        }
    }

    /**
     * 校验动作状态
     *
     * @param $attribute
     */
    public function checkStatus($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (!in_array($this->status, [Action::STATUS_INVALID, Action::STATUS_ENABLE])) {
            $this->addError($attribute, "参数错误[status_error]");
            return true;
        }
    }

    /**
     * 获取动作信息
     *
     * @return array|Action|null
     */
    public function getAction()
    {
        if (empty($this->action)) {
            $this->action = Yii::$app->services->action->findById($this->id);
        }

        return $this->action;
    }
}
